package xyz.ibenben.zhongdian.common.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.usermodel.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author chenjian
 * @since 2019-07-25
 */
@SuppressWarnings("unchecked")
public class WordConvertUtil {
    private static void writeFile(String content, String path) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            File file = new File(path);
            fos = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
            bw.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ignored) {

            }
        }
    }

    public static void convertDoc2Html(String fileName, String outPutFile) throws Exception {
        HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> {
            String type = pictureType.name();
            return "data:image/" + type + ";base64," + new String(Base64.encodeBase64(content));
        });
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();
        writeFile(new String(out.toByteArray()), outPutFile);
    }

    public static void convertDocx2Html(String fileName, String outPutFile) throws Exception {
        XWPFDocument document = new XWPFDocument(new FileInputStream(fileName));
        List<XWPFPictureData> list = document.getAllPictures();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, outputStream, null);
        String s = new String(outputStream.toByteArray());
        s = setImg(s, list);
        outputStream.close();
        writeFile(new String(s.getBytes(StandardCharsets.UTF_8)), outPutFile);
    }

    private static String setImg(String html, List<XWPFPictureData> list) {
        org.jsoup.nodes.Document doc = Jsoup.parse(html);
        Elements elements = doc.getElementsByTag("img");
        if (elements != null && elements.size() > 0 && list != null) {
            for (Element element : elements) {
                String src = element.attr("src");
                for (XWPFPictureData data : list) {
                    if (src.contains(data.getFileName())) {
                        String type = src.substring(src.lastIndexOf(".") + 1);
                        String base64 = "data:image/" + type + ";base64," +
                                new String(Base64.encodeBase64(data.getData()));
                        element.attr("src", base64);
                        break;
                    }
                }
            }
        }
        return doc.toString();
    }

    public static void searchAndReplaceDocx(String srcPath, String destPath, Map<String, Object> map) {
        CustomXWPFDocument doc;
        try {
            OPCPackage pack = POIXMLDocument.openPackage(srcPath);
            doc = new CustomXWPFDocument(pack);
            if (map != null && map.size() > 0) {

                //处理段落
                List<XWPFParagraph> paragraphList = doc.getParagraphs();
                processParagraphs(paragraphList, map, doc);

                //处理表格
                Iterator<XWPFTable> it = doc.getTablesIterator();
                while (it.hasNext()) {
                    XWPFTable table = it.next();
                    List<XWPFTableRow> rows = table.getRows();
                    for (XWPFTableRow row : rows) {
                        List<XWPFTableCell> cells = row.getTableCells();
                        for (XWPFTableCell cell : cells) {
                            List<XWPFParagraph> paragraphListTable = cell.getParagraphs();
                            processParagraphs(paragraphListTable, map, doc);
                        }
                    }
                }
            }
            FileOutputStream fopts = new FileOutputStream(destPath);
            doc.write(fopts);
            fopts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void searchAndReplaceDoc(String srcPath, String destPath, Map<String, String> map) {
        try {
            InputStream in = new FileInputStream(new File(srcPath));
            HWPFDocument wDoc = new HWPFDocument(in);
            Range range = wDoc.getRange();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                range.replaceText(entry.getKey(), entry.getValue());
            }
            OutputStream out = new FileOutputStream(new File(destPath));
            wDoc.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理段落
     *
     * @param paragraphList 段落列表
     */
    private static void processParagraphs(List<XWPFParagraph> paragraphList, Map<String, Object> param,
                                          CustomXWPFDocument doc) {
        if (paragraphList != null && !paragraphList.isEmpty()) {
            for (XWPFParagraph paragraph : paragraphList) {
                List<XWPFRun> runs = paragraph.getRuns();
                CopyOnWriteArrayList copyRuns = new CopyOnWriteArrayList(runs);
                processRuns(copyRuns, param, paragraph, doc);
            }
        }
    }

    private static void processRuns(CopyOnWriteArrayList<XWPFRun> runs, Map<String, Object> param, XWPFParagraph paragraph, CustomXWPFDocument doc) {
        if (runs != null && !runs.isEmpty()) {
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                if (text != null) {
                    boolean isSetText = false;
                    for (Entry<String, Object> entry : param.entrySet()) {
                        String key = entry.getKey();
                        if (text.contains(key)) {
                            isSetText = true;
                            Object value = entry.getValue();
                            //文本替换
                            if (value instanceof String) {
                                text = text.replace(key, value.toString());
                            } else if (value instanceof Map) {
                                //图片替换
                                text = text.replace(key, "");
                                Map pic = (Map) value;
                                int width = Integer.parseInt(pic.get("width").toString());
                                int height = Integer.parseInt(pic.get("height").toString());
                                int picType = getPictureType(pic.get("type").toString());
                                byte[] byteArray = (byte[]) pic.get("content");
                                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
                                try {
                                    doc.addPictureData(byteInputStream, picType);
                                    doc.createPicture(doc.getAllPictures().size() - 1, width, height, paragraph);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    if (isSetText) {
                        run.setText(text, 0);
                    }
                }
            }
        }
    }


    /**
     * 根据图片类型，取得对应的图片类型代码
     *
     * @param picType 图片扩展名
     * @return int
     */
    private static int getPictureType(String picType) {
        int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
        if (picType != null) {
            if ("png".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_PNG;
            } else if ("dib".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_DIB;
            } else if ("emf".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_EMF;
            } else if ("jpg".equalsIgnoreCase(picType) || "jpeg".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
            } else if ("wmf".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }

    /**
     * 将输入流中的数据写入字节数组
     *
     * @param in 输入流
     * @return 字节流
     */
    private static byte[] inputStream2ByteArray(InputStream in, boolean isClose) throws Exception {
        byte[] byteArray;
        try {
            int total = in.available();
            byteArray = new byte[total];
            in.read(byteArray);
        } finally {
            if (isClose) {
                in.close();
            }
        }
        return byteArray;
    }

    public static void main(String args[]) throws Exception {
        Map<String, Object> map = new HashMap<>(3);
        map.put("{A1}", "领导好");
        map.put("{B2}", "领导去死");
        map.put("{A3}", "领导去死");
        Map<String, Object> imgMap = new HashMap<>(3);
        imgMap.put("content", inputStream2ByteArray(new FileInputStream("C:\\Users\\admin\\Pictures\\微信图片_20181228135138.jpg"), true));
        imgMap.put("width", 200);
        imgMap.put("height", 200);
        imgMap.put("type", "jpg");
        map.put("{img1}", imgMap);
        try {
//            searchAndReplaceDoc("D://1.doc", "D://2.doc", map);
            searchAndReplaceDocx("D://1.docx", "D://2.docx", map);
//            convertDoc2Html("D://1.doc", "D://1.html");
//            convertDocx2Html("D://1.docx", "D://1.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
